package com.gnerv.pabu.basic.core.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class LogAspect {

    /**
     *
     * //@Pointcut("execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))")
     * 	//@Pointcut("within(com.test.spring.aop.pointcutexp..*)")
     * 	//@Pointcut("this(com.test.spring.aop.pointcutexp.Intf)")
     * 	//@Pointcut("target(com.test.spring.aop.pointcutexp.Intf)")
     * 	//@Pointcut("@within(org.springframework.transaction.annotation.Transactional)")
     * 	//@Pointcut("@annotation(org.springframework.transaction.annotation.Transactional)")
     */

    @Pointcut("execution(public * com.gnerv.pabu.basic.core.controller..*.*(..))")
    public void webLog() {
    }

    @Pointcut("within(com.gnerv.pabu.basic.annotation.EntityExtend)")
    public void within() {
    }

    @Pointcut("@annotation(com.gnerv.pabu.basic.annotation.EntityExtend)")
    public void annotation() {
    }

    /**
     * @within和@target针对类的注解,@annotation是针对方法的注解
     */
    @Pointcut("@within(com.gnerv.pabu.basic.annotation.EntityExtend)")
    public void withinClass() {
    }

    @Pointcut("webLog() || annotation()")
    private void logMessage(){}

    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        startTime.set(System.currentTimeMillis());
        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE : " + ret);
        log.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    }


}

